import React, { Component } from 'react';
import { Tabs, Table, Select, Button, Cascader, DatePicker, Radio, Spin } from 'antd';
import * as fetch from '../../utils/http'
import moment from 'moment';
import ReactEchars from '../history-data/history-echars';

const { Option } = Select;
const { TabPane } = Tabs;
const {RangePicker}=DatePicker;
const columns = [
    {
        title: '标签名',
        dataIndex: 'signNo',
        key: 'signNo',
        render: text => <b>{text}</b>,
    },
    {
        title: '标签编号',
        dataIndex: 'tag',
        key: 'tag',
    },
    {
        title: '时间',
        dataIndex: 'time',
        key: 'time',
    },
    {
        title: '当前值',
        dataIndex: 'value',
        key: 'value',
    }
];

class HistoryDataPage extends Component {
    constructor(props) {
        super(props)
        this.state = {
            data: [],
            // 开始时间
            startValue: null,
            // 结束时间
            endValue: null,
            //设备
            devices: [],
            //包含设备-子项-信号-tag等所有信息
            deviceInfo: [],
            //历史图表要用到的所有tag
            chartTags: [],
            isLoading: true,
            isChanging: false,
            deviceDefaultSelectValue: "",
            deviceItemDefaultSelectValue: "",
            deviceItemPropretyTagDefaultSelevtValue: "",
            chartXData: [],
            chartYData: [],
            legendData: [],
            endOpen: false,
            chartDeviceDefaultSelectValue: "",
            showChart: false,
            radioButtonDefaultValue: null,
            radioButtonSelectValue: null,
            showNextPreButton: false
        }
        this.getDeviceInfo();
        this.getDevices();
    }

    //
    getDevices() {
        fetch.get('RealTime/GetDevicesForApp').then(res => {
            this.setState({
                devices: res.data || [],
                deviceDefaultSelectValue: res.data[0].id,
                chartDeviceDefaultSelectValue: res.data[0].id,
            });
            //顺便把图表的也请求了
            this.getDeviceChartTag();
        })
    }
    //获取设备-子项-信号等级联数据
    getDeviceInfo() {
        fetch.get('RealTime/GetDeviceInfoForCascader').then(res => {
            var data = res.data;
            var firstDevice = data[0];
            var firstDeviceItem = data[0].children[0];
            var firstDeviceItemProperty = firstDeviceItem.children[0];
            this.setState({
                deviceInfo: data,
                isLoading: false,
                deviceDefaultSelectValue: firstDevice.value,
                deviceItemDefaultSelectValue: firstDeviceItem.value,
                deviceItemPropretyTagDefaultSelevtValue: firstDeviceItemProperty.value
            })
        })
    }

    getData() {
        let tag = this.state.deviceItemPropretyTagDefaultSelevtValue;
        if (this.state.startValue === null || this.state.endValue === null) {

            alert("请选择要查询的时间段！");
            return;
        }
        this.setState({
            isChanging: true
        })
        let start = this.state.startValue.format('YYYY-MM-DD HH:mm:ss');
        let end = this.state.endValue.format('YYYY-MM-DD HH:mm:ss');
        fetch.get('History/GetHistoryDataByMoreSteps?tags=' + tag + "&startTime=" + start + "&endTime=" + end).then(res => {
            this.setState({
                data: res.data || [],
                isChanging: false
            })
        })
    }

    getDeviceChartTag() {
        const deviceId = this.state.deviceDefaultSelectValue;
        fetch.get('History/GetChartTags?deviceID=' + deviceId).then(res => {
            var data = res.data || [];
            var allTagName = [];
            if (data.length > 0) {
                var tags = data.map((item) => {
                    if (!!item.tag) {
                        allTagName.push(item.tagChartName);
                        return item.tag;
                    }
                });
                this.setState({
                    chartTags: tags,
                    legendData: allTagName//多少条曲线
                });
            }
        })
    }

    getChartData() {
        let tag = this.state.chartTags.join("|");
        let start = this.state.startValue;
        let end = this.state.endValue;
        console.log("图表时间start:" + (start === null ? "" : start.format('YYYY-MM-DD HH:mm:ss')));
        console.log("图表时间end:" + (end === null ? "" : end.format('YYYY-MM-DD HH:mm:ss')));

        var now = moment();
        if (end === null) {
            end = now.format('YYYY-MM-DD HH:mm:ss');
        } else {
            end = this.state.endValue.format('YYYY-MM-DD HH:mm:ss');
        }

        if (start === null) {
            start = now.subtract(2, "hours").format('YYYY-MM-DD HH:mm:ss');
        } else {
            start = this.state.startValue.format('YYYY-MM-DD HH:mm:ss');
        }


        this.setState({
            showChart: true,
        })


        fetch.get('History/GetHistoryDataByMoreSteps?tags=' + tag + "&startTime=" + start + "&endTime=" + end).then(res => {
            var data = res.data;
            if (data.length > 0) {
                //组装数据
                var first = data[0];
                var firstTag = first.tag;
                var firstData = data.filter(function (item) {
                    if (item.tag == firstTag) {
                        return item.time;
                    }
                });
                //x轴数据
                var timeData = firstData.map((item) => {
                    return item.time;
                })
                //有多少条曲线
                var allTags = this.state.legendData;
                var allValues = [];
                allTags.map((item) => {
                    var tagValue = data.filter(function (d) {
                        return d.tagChartName == item;
                    });
                    var lowAxis = tagValue[0].lowAxis;
                    var highAxis = tagValue[0].highAxis;
                    allValues.push({
                        name: item,
                        value: tagValue,
                        lowAxis: lowAxis,
                        highAxis: highAxis
                    })
                });
                this.setState({
                    chartXData: timeData,
                    chartYData: allValues,
                    showChart: false
                })
            }
        })
    }





    render() {
        const { startValue, endValue } = this.state;

        const onDateChange=(value, dateString)=> {
            console.log("1:"+value[0].format('YYYY-MM-DD HH:mm:ss'));
            console.log("2:"+value[1].format('YYYY-MM-DD HH:mm:ss'));
        }

        const onOk=(value)=> {
            console.log("1ok:"+value[0].format('YYYY-MM-DD HH:mm:ss'));
            console.log("2ok:"+value[1].format('YYYY-MM-DD HH:mm:ss'));
            this.setState({
                startValue:value[0],
                endValue:value[1],
                showNextPreButton:false
            })
        }
        const callback = (key) => {
            console.log("key:" + key);
            if (key == 2) {
                var now = moment();
                this.setState({
                    endValue: now,
                    startValue:now.subtract(2,"hours"),
                    showNextPreButton: true
                })
                this.setState({
                    showChart: true,
                    radioButtonDefaultValue: "2h"
                })
                this.getChartData();
            } else {
                this.setState({
                    startValue: null,
                    endValue: null,
                    radioButtonDefaultValue: null
                })
            }
        }
        if (this.state.isLoading) {
            return (<div style={{ textAlign: 'center', height: 460 }}><Spin style={{ marginTop: '20%' }} /></div>);
        } else {
            const options = this.state.deviceInfo;
            const onChange = (value) => {
                this.setState({
                    deviceDefaultSelectValue: value[0],
                    deviceItemDefaultSelectValue: value[1],
                    deviceItemPropretyTagDefaultSelevtValue: value[2]
                })
            }
            const queryData = () => {
                this.getData();
            }

            const queryChartData = () => {
                this.getChartData();
            }

            const deviceList = this.state.devices.map((d) =>
                <Option key={d.id} value={d.id}>{d.name}</Option>
            );
            const handleChange = (deviceId) => {
                this.setState({
                    chartDeviceDefaultSelectValue: deviceId
                })
            }

            const timeRadioChange = (e) => {
                this.setState({
                    endValue: moment(),
                    radioButtonSelectValue: e.target.value,
                    showNextPreButton: true
                })
                var value = e.target.value;
                var starttime = null;
                var now = moment();
                if (value === "2h") {
                    starttime = now.subtract(2, 'hours');
                    console.log("start:" + starttime.format('YYYY-MM-DD HH:mm:ss'))
                }
                else if (value === "4h") {
                    starttime = now.subtract(4, 'hours');
                    console.log("start:" + starttime.format('YYYY-MM-DD HH:mm:ss'))
                }
                else if (value === "8h") {
                    starttime = now.subtract(8, 'hours');
                    console.log("start:" + starttime.format('YYYY-MM-DD HH:mm:ss'))
                }
                else if (value === "16h") {
                    starttime = now.subtract(16, 'hours');
                    console.log("start:" + starttime.format('YYYY-MM-DD HH:mm:ss'))
                }
                else if (value === "24h") {
                    starttime = now.subtract(24, 'hours');
                    console.log("start:" + starttime.format('YYYY-MM-DD HH:mm:ss'))
                }
                else if (value === "3d") {
                    starttime = now.subtract(3, 'days');
                    console.log("start:" + starttime.format('YYYY-MM-DD HH:mm:ss'))
                }
                else if (value === "1w") {
                    starttime = now.subtract(7, 'days');
                    console.log("start:" + starttime.format('YYYY-MM-DD HH:mm:ss'))
                }
                else if (value === "1m") {
                    starttime = now.subtract(30, 'days');
                    console.log("start:" + starttime.format('YYYY-MM-DD HH:mm:ss'))
                }
                this.setState({
                    startValue: starttime,
                })
            }

            const getStarttime = (start, splitValue, isAdd) => {
                var starttime = null;
                if (splitValue === "2h") {
                    if (isAdd) {
                        starttime = start.add(2, 'hours');
                    } else {
                        starttime = start.subtract(2, 'hours');
                    }
                }
                else if (splitValue === "4h") {
                    if (isAdd) {
                        starttime = start.add(4, 'hours');
                    } else {
                        starttime = start.subtract(4, 'hours');
                    }
                }
                else if (splitValue === "8h") {
                    if (isAdd) {
                        starttime = start.add(8, 'hours');
                    } else {
                        starttime = start.subtract(8, 'hours');
                    }
                }
                else if (splitValue === "16h") {
                    if (isAdd) {
                        starttime = start.add(16, 'hours');
                    } else {
                        starttime = start.subtract(16, 'hours');
                    }
                }
                else if (splitValue === "24h") {
                    if (isAdd) {
                        starttime = start.add(24, 'hours');
                    } else {
                        starttime = start.subtract(24, 'hours');
                    }
                }
                else if (splitValue === "3d") {

                    if (isAdd) {
                        starttime = start.add(3, 'days');
                    } else {
                        starttime = start.subtract(3, 'days');
                    }
                }
                else if (splitValue === "1w") {
                    if (isAdd) {
                        starttime = start.add(7, 'days');
                    } else {
                        starttime = start.subtract(7, 'days');
                    }
                }
                else if (splitValue === "1m") {
                    if (isAdd) {
                        starttime = start.add(30, 'days');
                    } else {
                        starttime = start.subtract(30, 'days');
                    }
                }
                this.setState({
                    startValue: starttime,
                })
            }
            const getEndtime = (end, splitValue, isAdd) => {
                var starttime = null;
                if (splitValue === "2h") {
                    if (isAdd) {
                        starttime = end.add(2, 'hours');
                    } else {
                        starttime = end.subtract(2, 'hours');
                    }
                }
                else if (splitValue === "4h") {
                    if (isAdd) {
                        starttime = end.add(4, 'hours');
                    } else {
                        starttime = end.subtract(4, 'hours');
                    }
                }
                else if (splitValue === "8h") {
                    if (isAdd) {
                        starttime = end.add(8, 'hours');
                    } else {
                        starttime = end.subtract(8, 'hours');
                    }
                }
                else if (splitValue === "16h") {
                    if (isAdd) {
                        starttime = end.add(16, 'hours');
                    } else {
                        starttime = end.subtract(16, 'hours');
                    }
                }
                else if (splitValue === "24h") {
                    if (isAdd) {
                        starttime = end.add(24, 'hours');
                    } else {
                        starttime = end.subtract(24, 'hours');
                    }
                }
                else if (splitValue === "3d") {

                    if (isAdd) {
                        starttime = end.add(3, 'days');
                    } else {
                        starttime = end.subtract(3, 'days');
                    }
                }
                else if (splitValue === "1w") {
                    if (isAdd) {
                        starttime = end.add(7, 'days');
                    } else {
                        starttime = end.subtract(7, 'days');
                    }
                }
                else if (splitValue === "1m") {
                    if (isAdd) {
                        starttime = end.add(30, 'days');
                    } else {
                        starttime = end.subtract(30, 'days');
                    }
                }
                this.setState({
                    endValue: starttime,
                })
            }
            //上一页
            const queryPreChartData = () => {
                var end = this.state.endValue;
                var start = this.state.startValue;
                var splitValue = this.state.radioButtonSelectValue;
                getEndtime(end, splitValue, false);
                getStarttime(start, splitValue, false);
                this.getChartData();
            }
            //下一页
            const queryNextChartData = () => {
                var end = this.state.endValue;
                var start = this.state.startValue;
                var splitValue = this.state.radioButtonSelectValue;
                getEndtime(end, splitValue, true);
                getStarttime(start, splitValue, true);
                this.getChartData();
            }
            return (
                <div>
                    <h3>历史数据</h3>
                    <Tabs
                        onChange={callback}
                        type="card"
                        bordered
                    >
                        <TabPane tab="历史数据" key="1">
                            <div style={{ marginTop: '10px' }}>
                                <label>设备信息：</label>
                                <Cascader
                                    defaultValue={[this.state.deviceDefaultSelectValue, this.state.deviceItemDefaultSelectValue, this.state.deviceItemPropretyTagDefaultSelevtValue]}
                                    options={options}
                                    onChange={onChange}
                                    style={{ width: '400px', marginRight: '10px' }}
                                />
                            </div>
                            <div style={{ marginTop: '10px' }}>
                                <label>时间选择：</label>
                                <Radio.Group defaultValue={this.state.radioButtonDefaultValue} buttonStyle="solid" style={{ marginRight: '10px' }} onChange={timeRadioChange}>
                                    <Radio.Button value="2h">最近2小时</Radio.Button>
                                    <Radio.Button value="4h">最近4小时</Radio.Button>
                                    <Radio.Button value="8h">最近8小时</Radio.Button>
                                    <Radio.Button value="16h">最近16小时</Radio.Button>
                                    <Radio.Button value="24h">最近24小时</Radio.Button>
                                    <Radio.Button value="3d">最近3天</Radio.Button>
                                    <Radio.Button value="1w">最近1周</Radio.Button>
                                    <Radio.Button value="1m">最近1月</Radio.Button>
                                </Radio.Group>

                            </div>
                            <div style={{ marginLeft: '70px' }}>
                                <RangePicker
                                    showTime={{ format: 'HH:mm:ss' }}
                                    format="YYYY-MM-DD HH:mm:ss"
                                    placeholder={['开始时间', '结束时间']}
                                    onChange={onDateChange}
                                    onOk={onOk}
                                    style={{ width: '400px'}}
                                />
                                <Button type="primary" style={{ margin: 10 }} onClick={queryData}>查询</Button>
                            </div>
                            <Table columns={columns} dataSource={this.state.data} rowKey="time" loading={this.state.isChanging} />
                        </TabPane>
                        <TabPane tab="历史图表" key="2">
                            <div style={{ marginTop: '10px' }}>
                                <label>设备信息：</label>
                                <Select defaultValue={this.state.chartDeviceDefaultSelectValue} style={{ width: 120, marginRight: '10px' }} onChange={handleChange} >
                                    {deviceList}
                                </Select>
                            </div>
                            <div style={{ marginTop: '10px' }}>
                                <label>时间选择：</label>
                                <Radio.Group defaultValue={this.state.radioButtonDefaultValue} buttonStyle="solid" style={{ marginRight: '10px' }} onChange={timeRadioChange}>
                                    <Radio.Button value="2h">最近2小时</Radio.Button>
                                    <Radio.Button value="4h">最近4小时</Radio.Button>
                                    <Radio.Button value="8h">最近8小时</Radio.Button>
                                    <Radio.Button value="16h">最近16小时</Radio.Button>
                                    <Radio.Button value="24h">最近24小时</Radio.Button>
                                    <Radio.Button value="3d">最近3天</Radio.Button>
                                    <Radio.Button value="1w">最近1周</Radio.Button>
                                    <Radio.Button value="1m">最近1月</Radio.Button>
                                </Radio.Group>

                            </div>
                            <div style={{ marginLeft: '70px' }}>
                                <RangePicker
                                    showTime={{ format: 'HH:mm:ss' }}
                                    format="YYYY-MM-DD HH:mm:ss"
                                    placeholder={['开始时间', '结束时间']}
                                    onChange={onDateChange}
                                    onOk={onOk}
                                    style={{ width: '400px'}}
                                />
                                <Button type="primary" style={{ margin: 10 }} onClick={queryChartData}>查询</Button>
                                <Button type="primary" style={{ margin: 10 }} onClick={queryPreChartData} disabled={!this.state.showNextPreButton}>上一页</Button>
                                <Button type="primary" style={{ margin: 10 }} onClick={queryNextChartData} disabled={!this.state.showNextPreButton}>下一页</Button>
                            </div>


                            <ReactEchars legendData={this.state.legendData} xDatas={this.state.chartXData} charsData={this.state.chartYData} showChart={this.state.showChart}></ReactEchars>
                        </TabPane>
                    </Tabs>
                </div>
            );
        }

    }
}

export default HistoryDataPage;